package cat.joronya.supermanager.team;

import java.text.NumberFormat;
import java.util.Locale;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.SimpleCursorAdapter.ViewBinder;
import android.widget.TextView;
import android.widget.Toast;
import cat.joronya.supermanager.DatabaseHelper;
import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.service.SupermanagerServiceHelper;

/**
 * Activity to list the user teams.
 * @author pol
 */
public class MyTeamsListActivity extends ListActivity 
{
	// pel Log
	private static final String TAG = "supermanager";
	
	/**
     * The columns we are interested in from the database
     */
    private static final String[] PROJECTION = new String[] {
            Supermanager.MyTeam._ID, 					// 0
            Supermanager.MyTeam.ID_EQU, 				// 1
            Supermanager.MyTeam.NAME, 					// 2
            Supermanager.MyTeam.DAY, 					// 3
            Supermanager.MyTeam.POINTS,					// 4
            Supermanager.MyTeam.GENERAL,				// 5
            Supermanager.MyTeam.BROKER,					// 6
            Supermanager.MyTeam.POINTS_CLASSIFICATION,	// 7
            Supermanager.MyTeam.GENERAL_CLASSIFICATION,	// 8
            Supermanager.MyTeam.BROKER_CLASSIFICATION,	// 9
            Supermanager.MyTeam.POINTS_BEST,			// 10
            Supermanager.MyTeam.POINTS_AVERAGE,			// 11
            Supermanager.MyTeam.BEST_CLASSIFICATION,	// 12
            Supermanager.MyTeam.MODIFIED_DATE 			// 13
    };
    
    // cursor de jornades actives.
    private Cursor daysCursor;
    
    // jornada que estem mostrant
    private int day = 0;
    
	/** 
	 * Called when the activity is first created. 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_teams_list);
    
		// amaguem el ProgressBar
        ProgressBar progressBar = (ProgressBar) findViewById(R.id.my_teams_list_loading);
        progressBar.setVisibility(View.INVISIBLE);
        
        // If no data was given in the intent, then use our default content provider.
        Intent intent = getIntent();
        Uri plUri = getIntent().getData();
        if( plUri == null) {
        	plUri = Supermanager.MyTeam.CONTENT_URI;
            intent.setData(Supermanager.MyTeam.CONTENT_URI);
        }
	
        // recuperem les jornades diferents.
        MyTeamsProvider myTeamsProvider = new MyTeamsProvider();
        daysCursor = myTeamsProvider.getDays(this);
        
        // per defecte agafem el primer
        if( daysCursor.moveToFirst() )
        {
        	day= daysCursor.getInt(0);
        }
        
        // Mostrem la jornada actual a la capçalera
        TextView dayTextVieww = (TextView) findViewById(R.id.my_teams_list_jornada);
        dayTextVieww.setText(getResources().getString(R.string.my_teams_list_jornada, new Integer(day).toString()));
        
        // filtrem els equips per la jornada triada
        Cursor cursor = managedQuery(getIntent().getData(), 
        		PROJECTION, 
        		Supermanager.MyTeam.DAY + " = ? ", 
        		new String[]{new Integer(day).toString()},
                Supermanager.MyTeam.DEFAULT_SORT_ORDER);
        
		// Used to map notes entries from the database to views
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
        		R.layout.my_teams_list_row, 
        		cursor,
                new String[] { Supermanager.MyTeam.ID_EQU,
        					   Supermanager.MyTeam.NAME,
        					   Supermanager.MyTeam.POINTS,
        					   Supermanager.MyTeam.POINTS_CLASSIFICATION,
        					   Supermanager.MyTeam.GENERAL,
        					   Supermanager.MyTeam.GENERAL_CLASSIFICATION,
        					   Supermanager.MyTeam.BROKER,
        					   Supermanager.MyTeam.BROKER_CLASSIFICATION }, 
        		new int[] { R.id.my_teams_list_row_id,
        					R.id.my_teams_list_row_name,
        					R.id.my_teams_list_row_jornada,
        					R.id.my_teams_list_row_jornada2,
        					R.id.my_teams_list_row_general,
        					R.id.my_teams_list_row_general2,
        					R.id.my_teams_list_row_broker,
        					R.id.my_teams_list_row_broker2 });
        
        final NumberFormat nf = NumberFormat.getInstance(new Locale("es", "es"));
        
        adapter.setViewBinder(new ViewBinder()
        {
        	public boolean setViewValue(View aView, Cursor aCursor, int aColumnIndex)
        	{
        		// points
        		if( aColumnIndex == 4 )
        		{
        			float value = aCursor.getFloat(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText(nf.format(value));
        			return true;
        		}
        		// general
        		if( aColumnIndex == 5 )
        		{
        			float value = aCursor.getFloat(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText(nf.format(value));
        			return true;
        		}
        		// broker
        		if( aColumnIndex == 6 )
        		{
        			int value = aCursor.getInt(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText(nf.format(value));
        			return true;
        		}
        		// classifications jornada
        		if( aColumnIndex == 7 )
        		{
        			int value = aCursor.getInt(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText("("+nf.format(value)+"º)");
        			return true;
        		}
        		// classifications general
        		if( aColumnIndex == 8 )
        		{
        			int value = aCursor.getInt(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText("("+nf.format(value)+"º)");
        			return true;
        		}
        		// classifications broker
        		if( aColumnIndex == 9 )
        		{
        			int value = aCursor.getInt(aColumnIndex);
        			TextView textView = (TextView) aView;
        			textView.setText("("+nf.format(value)+"º)");
        			return true;
        		}
        		return false;
        	}
        });
        
        setListAdapter(adapter);
	}
	
	/**
	 * Al clicar un team anem al detall.
	 */
	protected void onListItemClick (ListView l, View v, int position, long id)
	{
		Log.d(TAG,"veient detall de team amb _id: "+id);
		// mostrem l'activitat del detall de l'equip
		// TODO: passar nom lliga i jornada
		startActivity(new Intent(this,MyTeamDetailActivity.class)
			.setData(Supermanager.MyTeamDetail.CONTENT_URI)
			.putExtra("cat.joronya.supermanager.myteams.id", id)
			.putExtra("cat.joronya.supermanager.myteams.day", 34));
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.my_teams_list, menu);
        return true;
    }

	@Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
        // Handle item selection
		switch (item.getItemId()) 
		{
			case R.id.refresh:
				Log.d(TAG,"refreshing my teams list");
				// mostrem el ProgressBar
		        ProgressBar progressBar = (ProgressBar) findViewById(R.id.my_teams_list_loading);
		        progressBar.setVisibility(View.VISIBLE);
		        
				// cridar refresh al REST method
				SupermanagerServiceHelper.getInstance(this).getMyTeams(handler);
				break;
		}

		return true;
    }
	
    private Handler handler = new Handler() 
    { 
        @Override 
        public void handleMessage(Message msg)
        { 
            //get data from msg 
        	int status = msg.getData().getInt(Supermanager.STATUS_MESSAGE);
            Log.d(TAG, "MyTeamsListActivity received status: "+status);
            
            // TODO: check auth error, connectivity error, closed error, other error
            if( status == Supermanager.MY_TEAMS_PARSED_OK )
            {
            	// amaguem el ProgressBar
		        ProgressBar progressBar = (ProgressBar) findViewById(R.id.my_teams_list_loading);
		        progressBar.setVisibility(View.INVISIBLE);
		        
		        Toast.makeText(getApplicationContext(), 
		        	R.string.my_teams_list_toast_refresh_done, 
            		Toast.LENGTH_SHORT).show();
            }
            
            super.handleMessage(msg); 
        } 
    };

}
